package com.waypolice.manager.controller;

import com.waypolice.common.constant.BorrowConstant;
import com.waypolice.common.pojo.EasyUiDataGridResult;
import com.waypolice.common.pojo.TaotaoResult;
import com.waypolice.common.utils.MathUtils;
import com.waypolice.manager.service.*;
import com.waypolice.mapper.CmsJudItemMapper;
import com.waypolice.mapper.CmsJudVolumeMapper;
import com.waypolice.pojo.*;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * 档案著录
 * @author zry
 *
 */
@Controller
@Api(value = "档案", description = "档案著录")
@RequestMapping(value="/pcwindow")
public class ArcCreateAction {

	private static final Logger LOGGER = LoggerFactory.getLogger(ArcCreateAction.class);

	@Autowired
	private ArcCreateService arcCreateService;
	@Autowired
	private VolAndItemService volAndItemService;
	@Autowired
	private UpmsArchivesTypesService upmsArchivesTypesService;
	@Autowired
	private UpmsDictionaryService upmsDictionaryService;
	@Autowired
	private UpmsOrganizationService upmsOrganizationService;
	@Autowired
	private CmsJudVolumeMapper cmsJudVolumeMapper;
	@Autowired
	private CmsJudItemMapper cmsJudItemMapper;

	/**
	 * 档案著录页面跳转
	 *
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/arcCreate")
	public String userManagerJump(HttpServletResponse response, HttpServletRequest request,
								  String volIdToDetils,String position) {
		if(StringUtils.isNotBlank(volIdToDetils)){
			if(StringUtils.isNotBlank(position)){
				request.setAttribute("position",position);
			}else {
				request.setAttribute("position","undefined");
			}
			request.setAttribute("volIdToDetils",volIdToDetils);
		}else {
			request.setAttribute("volIdToDetils","undefined");

		}
		return "/preArchive/arcCreate";
	}

	/**
	 * 添加卷著录信息
	 *
	 * @return user
	 */
	@ApiOperation(value = "添加卷著录信息")
	@RequestMapping(value = "/insertJudMessage")
	@ResponseBody
	public TaotaoResult insertJudMessage(HttpServletRequest request, HttpServletResponse response) {
		TaotaoResult result = new TaotaoResult();
		//案卷Id
		String volId = request.getParameter("volId");
		//案卷类型
		String vol_class = request.getParameter("arcType");
		//保管期限
		String vol_storagetime = request.getParameter("arcDeadline");
		//档号
		String vol_no = request.getParameter("arcNumber");
		//全宗号
		String vol_Fian = request.getParameter("allArcNumber");
		//案卷题名
		String vol_title = request.getParameter("judTitle");
		//归档年度
		String vol_arcyear = request.getParameter("arcYear");
		//归档单位
		String vol_arcunit = request.getParameter("arcApartment");
		//审计组长
		String vol_auditleader = request.getParameter("auditPersosn");
		//审计起始日期
		String vol_auditdate = request.getParameter("auditDate");
		//卷内起始日期
		String vol_insidedate = request.getParameter("judStartDate");
		//密级
		String vol_secret = request.getParameter("secretLevel");
		//保密期限
		String secretDateline = request.getParameter("secretDateline");
		//总卷数
		String vol_total = request.getParameter("allJudNumber");
		//当前卷数
		String vol_current = request.getParameter("presentJudNumber");
		//页数
		String vol_totalpage = request.getParameter("pageNumber");
		//备注
		String vol_desc = request.getParameter("judRemarks");
		//是否公开
		String volPublicStatus = request.getParameter("volPublicStatus");
		//载体类型
		String volCarrier = request.getParameter("volCarrier");
		//件数
		String volItemNumber = request.getParameter("volItemNumber");
		if(StringUtils.isBlank(volId)){
			result = arcCreateService.inserJudVolMessage(volItemNumber,volCarrier,volPublicStatus,vol_class, vol_storagetime, vol_no, vol_Fian, vol_title, vol_arcyear, vol_arcunit, vol_auditleader,
					vol_auditdate, vol_insidedate, vol_secret,secretDateline, vol_total, vol_current, vol_totalpage, vol_desc);
		}else{
			CmsJudVolume cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(Long.valueOf(volId));
			if(cmsJudVolume.getVolArchiveStatus() == 2){
			//档案已归档，提交归档
				result = arcCreateService.submitJudVolMessageAndArchive(volItemNumber,volCarrier,volPublicStatus,volId,vol_class, vol_storagetime, vol_no, vol_Fian, vol_title, vol_arcyear, vol_arcunit, vol_auditleader,
						vol_auditdate, vol_insidedate, vol_secret,secretDateline, vol_total, vol_current, vol_totalpage, vol_desc);
			}else{
				//档案未归档，更新
				result = arcCreateService.updateJudVolMessage(volItemNumber,volCarrier,volPublicStatus,volId,vol_class, vol_storagetime, vol_no, vol_Fian, vol_title, vol_arcyear, vol_arcunit, vol_auditleader,
						vol_auditdate, vol_insidedate, vol_secret,secretDateline, vol_total, vol_current, vol_totalpage, vol_desc);
			}

		}
		return result;
	}

	/**
	 * 添加件著录信息
	 *
	 * @return user
	 */
	@ApiOperation(value = "添加件")
	@RequestMapping(value = "/insertItemMessage")
	@ResponseBody
	public TaotaoResult insertItemMessage(HttpServletRequest request, HttpServletResponse response) {
		TaotaoResult result = new TaotaoResult();
		//所属件Id
		String itemId = request.getParameter("itemId");
		//所属卷Id
		String volId = request.getParameter("volId");
		//序号
		String itemNumber = request.getParameter("itemNumber");
		//页次
		String itemPageNumber = request.getParameter("itemPageNumber");
		//单元号
		String partNumber = request.getParameter("partNumber");
		//发文日期
		String itemStartDate = request.getParameter("itemStartDate");
		//题名
		String itemTitle = request.getParameter("itemTitle");
		//文号
		String itemFileNumber = request.getParameter("itemFileNumber");
		//密级
		String itemSecretLevel = request.getParameter("itemSecretLevel");
		//保密期限
		String itemSecretDateline = request.getParameter("itemSecretDateline");
		//责任者
		String dutyPerson = request.getParameter("dutyPerson");
		String itemStr5 = request.getParameter("itemStr5");
		CmsJudVolume cmsJudVolume = cmsJudVolumeMapper.selectByPrimaryKey(Long.valueOf(volId));
		if(StringUtils.isBlank(itemId)){
			if(cmsJudVolume.getVolArchiveStatus() == 2){
				//档案已归档，提交归档,插入新的生成档号
				result = arcCreateService.submitInsertJudItemMessageArchive(itemStr5,volId, itemNumber, itemPageNumber, partNumber, itemStartDate, itemTitle, itemFileNumber, itemSecretLevel,itemSecretDateline,
						dutyPerson);
			}else{
				//档案未归档，新插入
				result = arcCreateService.inserJudItemMessage(itemStr5,volId, itemNumber, itemPageNumber, partNumber, itemStartDate, itemTitle, itemFileNumber, itemSecretLevel,itemSecretDateline,
						dutyPerson);
			}
		}else{
			if(cmsJudVolume.getVolArchiveStatus() == 2){
				//档案已归档，更新归档信息
				result = arcCreateService.submitJudItemMessageArchive(itemStr5,itemId,volId, itemNumber, itemPageNumber, partNumber, itemStartDate, itemTitle, itemFileNumber, itemSecretLevel,itemSecretDateline,
						dutyPerson);
			}else{
				//档案未归档，更新
				result = arcCreateService.updateJudItemMessage(itemStr5,itemId,volId, itemNumber, itemPageNumber, partNumber, itemStartDate, itemTitle, itemFileNumber, itemSecretLevel,itemSecretDateline,
						dutyPerson);
			}

		}
		return result;
	}

	/**
	 * 根据卷Id查询卷
	 *
	 * @return
	 */
	@ApiOperation(value = "根据卷Id查询卷")
	@RequestMapping(value = "/findJudMessageByVolId")
	@ResponseBody
	public Object findJudMessageByVolId(HttpServletRequest request, HttpServletResponse response) {
		String volId = request.getParameter("volId");
		CmsJudVolume cmsJudVolume = volAndItemService.selectCmsJudVolumeByVolId(Long.valueOf(volId));
		return cmsJudVolume;
	}

	@ApiOperation(value = "档案卷修改数据回显")
	@RequestMapping(value = "/findItemList")
	@ResponseBody
	public Object findItemList(@RequestParam(required = false, value = "volId") long volId) {
		List<CmsJudItem> itemlists = volAndItemService.selectAllByVolId(volId,1);
		Map<String, Object> result = new HashMap<>(2);
		if (!itemlists.isEmpty()) {
			result.put("rows", itemlists);
			result.put("total", itemlists.size());
		}
		return result;
	}
	/**
	 * 根据最大件序号
	 *
	 * @return
	 */
	@ApiOperation(value = "根据最大件序号")
	@RequestMapping(value = "/findMaxItemNumber")
	@ResponseBody
	public Object findMaxItemNumber(HttpServletRequest request, HttpServletResponse response) {
		String volId = request.getParameter("volId");
		long itemNumber= arcCreateService.selectMaxItemNumber(volId);
		return itemNumber;
	}

	/**
	 * 根据Id查询卷内件列表，并显示第一个件
	 * @return
	 */
	@ApiOperation(value = "根据Id查询卷")
	@RequestMapping(value = "/showItemMessages")
	@ResponseBody
	public Object showItemMessages(HttpServletRequest request, HttpServletResponse response) {
		String volId = request.getParameter("volId");
		List<CmsJudItem> itemlists = volAndItemService.selectAllByVolId(Long.valueOf(volId),1);
		Map<String, Object> result = new HashMap<>(2);
		if (!itemlists.isEmpty()) {
			result.put("rows", itemlists);
			result.put("total", itemlists.size());
		}
		return result;
	}
	/**
	 * 根据Id查询件信息
	 * @return
	 */
	@ApiOperation(value = "根据Id查询件")
	@RequestMapping(value = "/showItemMessagesByItemId")
	@ResponseBody
	public Object showItemMessagesByItemId(HttpServletRequest request, HttpServletResponse response) {
		String itemId = request.getParameter("itemId");
		CmsJudItem cmsJudItem = arcCreateService.selectCmsJudItemByItemId(Long.valueOf(itemId));
		return cmsJudItem;
	}
	/**
	 * 查询全部案卷类型
	 * @param response
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "查询全部案卷类型")
	@RequestMapping(value = "/findAllJudType")
	@ResponseBody
	public Object findAllJudType(HttpServletResponse response, HttpServletRequest request) {
		List<UpmsArchivesTypes> types = upmsArchivesTypesService.findAllTypes();
		Map<String, Object> result = new HashMap<>(2);
		result.put("rows",types);
		return result;
	}
	/**
	 * 查询全部保存期限
	 * @param response
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "查询全部保存期限")
	@RequestMapping(value = "/findAllStorageTime")
	@ResponseBody
	public Object findAllStorageTime(HttpServletResponse response, HttpServletRequest request) {
		List<UpmsDictionary> types = upmsDictionaryService.findAllStorageTime();
		Map<String, Object> result = new HashMap<>(2);
		result.put("rows",types);
		return result;
	}

	/**
	 * 查询全部密级
	 * @param response
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "查询全部密级")
	@RequestMapping(value = "/findAllSecretLevel")
	@ResponseBody
	public Object findAllSecretLevel(HttpServletResponse response, HttpServletRequest request) {
		List<UpmsDictionary> findAllSecretLevel = upmsDictionaryService.findAllSecretLevel();
		Map<String, Object> result = new HashMap<>(2);
		result.put("rows",findAllSecretLevel);
		return result;
	}

	/**
	 * 根据档案编号查询保存期限
	 * @param response
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "根据档案编号查询保存期限")
	@RequestMapping(value = "/findStorageTimeTypeByCode")
	@ResponseBody
	public Object findStorageTimeTypeByCode(HttpServletResponse response, HttpServletRequest request) {
		String volClass = request.getParameter("volClass");
		List<UpmsDictionary> types = upmsDictionaryService.findStorageTimeTypeByCode(volClass);
		return types;
	}
    /**
     * 根据档案编号查询案卷类型
     * @param response
     * @param request
     * @return
     */
    @ApiOperation(value = "根据档案编号查询案卷类型")
    @RequestMapping(value = "/findArchiveTypeByArchiveNum")
    @ResponseBody
    public Object findArchiveTypeByArchiveNum(HttpServletResponse response, HttpServletRequest request) {
        String volClass = request.getParameter("volClass");
        List<UpmsArchivesTypes> types = upmsArchivesTypesService.findArchiveTypeByArchiveNum(volClass);
        return types;
    }

	/**
	 * 案卷号不重复
	 *
	 * @return user
	 */
	@ApiOperation(value = "案卷号不重复")
	@RequestMapping(value = "/findarcNumber")
	@ResponseBody
	public TaotaoResult findarcNumber(HttpServletRequest request, HttpServletResponse response) {
		TaotaoResult result = new TaotaoResult();
		String volId = request.getParameter("volId");
		String arcNumber = request.getParameter("arcNumber");
		result = arcCreateService.findSameArcNumber(volId,arcNumber);
		return result;
	}

    /**
     * 案卷号不重复
     *
     * @return user
     */
    @ApiOperation(value = "案卷号不重复")
    @RequestMapping(value = "/findItemPage")
    @ResponseBody
    public TaotaoResult findItemPage(HttpServletRequest request, HttpServletResponse response) {
        TaotaoResult result = new TaotaoResult();
        String itemId = request.getParameter("itemId");
        String volId = request.getParameter("volId");
        String itemPageNumber = request.getParameter("itemPageNumber");
        result = arcCreateService.findSameItemPage(itemId,volId,itemPageNumber);
        return result;
    }
	/**
	 * 查询全部案卷类型
	 * @param response
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "根据档案编号查询案卷类型")
	@RequestMapping(value = "/findItemNumberIsRepeat")
	@ResponseBody
	public TaotaoResult findItemNumberIsRepeat(HttpServletResponse response, HttpServletRequest request) {
		TaotaoResult result = new TaotaoResult();
		String itemNumber = request.getParameter("itemNumber");
		String volId = request.getParameter("volId");
		result = arcCreateService.findItemNumberIsRepeat(itemNumber,volId);
		return result;
	}
	/**
	 * 删除件著录信息
	 *
	 * @return user
	 */
	@ApiOperation(value = "删除件")
	@RequestMapping(value = "/deleteArcItem")
	@ResponseBody
	public TaotaoResult deleteArcItem(HttpServletRequest request, HttpServletResponse response) throws Exception {
		TaotaoResult result = new TaotaoResult();
		String itemId = request.getParameter("itemId");
		//0:删除件 1：a删除件、关联关系、原文
		String type = request.getParameter("type");
		result = arcCreateService.deleteItemMessage(itemId,type);
		return result;
	}

	/**
	 * @author:zyp
	 * @description 获取件的id 展示至'我的借阅'
	 * @date: 2019/3/21 17:11
	 * @return 
	 */
	@ApiOperation(value = "获取件的id 展示至 我的借阅")
	@RequestMapping(value = "/getItemForMyBorrow")
	@ResponseBody
	public String getItemForMyBorrow(@RequestParam(required = false, value = "parentid") String parentid,
									 @RequestParam(required = false, value = "fileShape") long fileShape
	) throws Exception {
		JSONArray jsonArray = volAndItemService.getItemForMyBorrow(parentid,fileShape);
//		JSONArray jsonArray = JSONArray.fromObject(itemlists);
		String string = jsonArray.toString();
		return string;
	}

	/**
	 * 根据档案编号查询案卷类型
	 * @param response
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "根据档案编号查询案卷类型")
	@RequestMapping(value = "/findAllOrg")
	@ResponseBody
	public Object findAllOrg(HttpServletResponse response, HttpServletRequest request) {
		// 所有组织
		List<UpmsOrganization> upmsOrganizations = upmsOrganizationService.selectByExample(new UpmsOrganizationExample());
        return upmsOrganizations;
	}

	/**
	 * 保存卷校验件页次小于卷的页数
	 *
	 * @return user
	 */
	@ApiOperation(value = "校验页次")
	@RequestMapping(value = "/checkItemPageAndVolumePage")
	@ResponseBody
	public TaotaoResult checkItemPageAndVolumePage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		TaotaoResult result = new TaotaoResult();
		String volId = request.getParameter("volId");
		String pageNumber = request.getParameter("pageNumber");
		if(!"".equals(volId)){
			List<CmsJudItem> cmsJudIt = volAndItemService.selectAllByVolId(Long.valueOf(volId), 2);
			ArrayList<Long> objects = new ArrayList<>();
			for (CmsJudItem cmsJudItem : cmsJudIt) {
				//获取页次,为页数校验提供依据
				objects.add(Long.valueOf(cmsJudItem.getItemPage()));
			}
			Collections.reverse(objects);
			if(objects.size()!=0L){
				Long aLong = objects.get(0);
				//校验页次
				if(aLong>Long.valueOf(pageNumber) || objects.size()==0L ||
						org.apache.commons.lang3.StringUtils.isBlank(pageNumber)){
					result.setStatus(104);
					result.setMsg("最大件的页次需小于卷的页数!");
					return result;
				}
			}
		}
		result.setStatus(200);
		return result;
	}


	/**
	 * 保存件，校验件页次小于卷的页数
	 *
	 * @return user
	 */
	@ApiOperation(value = "校验页次")
	@RequestMapping(value = "/saveItemCheckItemPageAndVolumePage")
	@ResponseBody
	public TaotaoResult saveItemCheckItemPageAndVolumePage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		TaotaoResult result = new TaotaoResult();
		String volId = request.getParameter("volId");
		String pageNumber = request.getParameter("pageNumber");
		String itemPageNumber = request.getParameter("itemPageNumber");
		List<CmsJudItem> cmsJudIt = volAndItemService.selectAllByVolId(Long.valueOf(volId), 2);
		ArrayList<Long> objects = new ArrayList<>();
		objects.add(Long.valueOf(itemPageNumber));
		for (CmsJudItem cmsJudItem : cmsJudIt) {
			//获取页次,为页数校验提供依据
			objects.add(Long.valueOf(cmsJudItem.getItemPage()));
		}
		for( int i = 0 ; i < objects.size() - 1 ; i ++ )  {
			for  ( int  j  =  objects.size() - 1 ; j  >  i; j -- )  {
				if  (objects.get(j).equals(objects.get(i)))  {
					objects.remove(j);
				}
			}
		}
		Collections.sort(objects);
		Collections.reverse(objects);
		Long aLong = objects.get(0);
		//校验页次
		if(aLong>Long.valueOf(pageNumber) || objects.size()==0L ||
				org.apache.commons.lang3.StringUtils.isBlank(pageNumber)){
			result.setStatus(104);
			result.setMsg("最大件的页次需小于卷的页数!");
			return result;
		}
		result.setStatus(200);
		return result;
	}
}